package com.aliwo.service.impl;

import com.aliwo.config.WeChatConfig;
import com.aliwo.domain.User;
import com.aliwo.domain.Video;
import com.aliwo.domain.VideoOrder;
import com.aliwo.dto.VideoOrderDto;
import com.aliwo.mapper.UserMapper;
import com.aliwo.mapper.VideoMapper;
import com.aliwo.mapper.VideoOrderMapper;
import com.aliwo.service.VideoOrderService;
import com.aliwo.utils.CommonUtils;
import com.aliwo.utils.HttpUtils;
import com.aliwo.utils.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * .
 *
 * @author Xu Yayuan
 * @date 2021/11/27
 */
@Service
public class VideoOrderServiceImpl implements VideoOrderService {

    @Autowired
    private VideoMapper videoMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private VideoOrderMapper videoOrderMapper;

    @Autowired
    private WeChatConfig weChatConfig;

    @Transactional
    @Override
    public String save(VideoOrderDto videoOrderDto) {
        //查找视频信息
        Video video = videoMapper.getVideoById(videoOrderDto.getVideoId());
        //查找用户信息
        User user = userMapper.getUserById(videoOrderDto.getUserId());
        //生成订单
        VideoOrder videoOrder = new VideoOrder();
        videoOrder.setTotalFee(video.getPrice());
        videoOrder.setVideoImg(video.getCoverImg());
        videoOrder.setVideoTitle(video.getTitle());
        videoOrder.setVideoId(video.getId());
        videoOrder.setState(0);
        videoOrder.setUserId(user.getId());
        videoOrder.setHeadImg(user.getHeadImg());
        videoOrder.setNickname(user.getName());
        videoOrder.setDel(0);
        videoOrder.setIp(videoOrderDto.getIp());
        videoOrder.setOutTradeNo(CommonUtils.generateUUID());
        videoOrderMapper.save(videoOrder);
        // 生成签名 统一下单
        String codeUrl = null;
        try {
            codeUrl = this.unifiedOrder(videoOrder);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 返回codeurl
        return codeUrl;
    }

    /**
     * 统一下单方法
     *
     * @return
     */
    private String unifiedOrder(VideoOrder videoOrder) {
        //生成签名
        SortedMap<String, String> params = new TreeMap<>();
        params.put("appid", weChatConfig.getAppid());
        params.put("mch_id", weChatConfig.getMchId());
        params.put("nonce_str", CommonUtils.generateUUID());
        params.put("body", videoOrder.getVideoTitle());
        params.put("out_trade_no", videoOrder.getOutTradeNo());
        params.put("total_fee", videoOrder.getTotalFee().toString());
        params.put("spbill_create_ip", videoOrder.getIp());
        params.put("notify_url", weChatConfig.getPayCallbackUrl());
        params.put("trade_type", "NATIVE");
        //sign签名
        String sign = WXPayUtil.createSign(params, weChatConfig.getKey());
        params.put("sign", sign);
        //map转xml
        String payXml = null;
        try {
            payXml = WXPayUtil.mapToXml(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //统一下单
        String orderStr = HttpUtils.doPost(WeChatConfig.getUnifiedOrderUrl(), payXml, 4000);
        if (null == orderStr) {
            return null;
        }
        Map<String, String> unifiedOrderMap = null;
        try {
            unifiedOrderMap = WXPayUtil.xmlToMap(orderStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(unifiedOrderMap.toString());
        if (unifiedOrderMap != null) {
            return unifiedOrderMap.get("code_url");
        }
        return null;
    }

    @Override
    public VideoOrder findByOutTradeNo(String outTradeNo) {
        return videoOrderMapper.selectByOutTradeNo(outTradeNo);
    }

    @Override
    public int updateVideoOderByOutTradeNo(VideoOrder videoOrder) {
        return videoOrderMapper.updateVideoOrderByOutTradeNo(videoOrder);
    }
}
